<?php
class ArrayList implements Iterator
{
    private array $elements = array();
    private int $index=0;

    public function size(): int
    {
        return count($this->elements);
    }

    public function isEmpty(): bool
    {
        return empty($this->elements);
    }

    public function contains($value): bool
    {
        return in_array($value, $this->elements);
    }

    public function toArray(): array
    {
        return $this->elements;
    }

    public function add($element): bool
    {
        $this->elements[] = $element;
        return true;
    }

    public function remove($index): bool
    {
        if (isset($this->elements[$index])) {
            unset($this->elements[$index]);
            // Reindex the array after removal
            $this->elements = array_values($this->elements);
            return true;
        } else {
            return false;
        }
    }

    public function get($index)
    {
        return $this->elements[$index] ?? null;
    }

    public function indexOf($value): int
    {
        $index = array_search($value, $this->elements);
        return ($index !== false) ? $index : -1;
    }

    public function lastIndexOf($value): int
    {
        $index = array_search($value, array_reverse($this->elements, true));
        return ($index !== false) ? count($this->elements) - 1 - $index : -1;
    }

    public function subList(int $fromIndex, int $toIndex = -1): ArrayList
    {
        if ($toIndex === -1) {
            $toIndex = count($this->elements);
        }
        $subList = new ArrayList();
        $subList->elements = array_slice($this->elements, $fromIndex, $toIndex - $fromIndex);
        return $subList;
    }

    public static function toArrayList(array $arr):ArrayList{
        $newArrayList = new ArrayList();
        $newArrayList->elements = $arr;
        return $newArrayList;
    }
    public function addArrayList(ArrayList $arrayList){
        $this->elements = array_merge($this->elements,$arrayList->toArray());
    }

    public function clear()
    {
        $this->elements = array();
    }

    public function current()
    {
        return $this->get($this->index);
    }

    public function next()
    {
        ++$this->index;
    }

    public function key(): int
    {
        return $this->index;
    }

    public function valid(): bool
    {
        return isset($this->elements[$this->index]);
    }

    public function rewind()
    {
        $this->index = 0;
    }
}
